<template>
  <div class="search">
    <Card>
      <Row class="operation">
        <Button @click="addMenu" type="primary" icon="md-add">添加子节点</Button>
        <Button @click="addRootMenu" icon="md-add">添加一级菜单</Button>
        <Button @click="delAll" icon="md-trash">批量删除</Button>
        <Dropdown @on-click="handleDropdown">
          <Button>
            更多操作
            <Icon type="md-arrow-dropdown"></Icon>
          </Button>
          <DropdownMenu slot="list">
            <DropdownItem name="refresh">刷新</DropdownItem>
            <DropdownItem name="expandOne">仅显示一级</DropdownItem>
            <DropdownItem name="expandTwo">仅展开两级</DropdownItem>
            <DropdownItem name="expandAll">展开所有</DropdownItem>
          </DropdownMenu>
        </Dropdown>
      </Row>
      <Row type="flex" justify="start" class="code-row-bg">
        <Col span="6">
        <Alert show-icon>
          当前选择编辑： <span class="select-title">{{editTitle}}</span>
          <a class="select-clear" v-if="menuForm.id" @click="canelEdit">取消选择</a>
        </Alert>
        <Input v-model="searchKey" suffix="ios-search" @on-change="search" placeholder="输入菜单名搜索" clearable/>
        <div class="tree-bar">
          <Tree ref="tree" :data="data" show-checkbox @on-check-change="changeSelect" @on-select-change="selectTree"></Tree>
        </div>
        <Spin size="large" fix v-if="loading"></Spin>
        </Col>
        <Col span="9">
        <Form ref="menuForm" :model="menuForm" :label-width="85" :rules="menuFormValidate">
          <FormItem label="类型" prop="type">
            <RadioGroup v-model="menuForm.type">
              <Radio :label="0" :disabled="isButton">
                <Icon type="ios-list-box-outline" size="16" style="margin-bottom:3px;"></Icon>
                <span>页面菜单</span>
              </Radio>
              <Radio :label="1" :disabled="isMenu">
                <Icon type="md-log-in" size="16" style="margin-bottom:3px;"></Icon>
                <span>操作按钮</span>
              </Radio>
            </RadioGroup>
          </FormItem>
          <FormItem label="名称" prop="title" v-if="menuForm.type===0">
            <Input v-model="menuForm.title"/>
          </FormItem>
          <FormItem label="名称" prop="title" v-if="menuForm.type===1">
            <Poptip trigger="focus" placement="right" width="230" word-wrap title="提示" content="操作按钮名称不得重复">
              <Input v-model="menuForm.title"/>
            </Poptip>
          </FormItem>
          <FormItem label="路径" prop="path" v-if="menuForm.type===0">
            <Input v-model="menuForm.path"/>
          </FormItem>
          <FormItem label="请求路径" prop="path" v-if="menuForm.type===1">
            <Poptip trigger="focus" placement="right" width="230" word-wrap title="提示" content="填写后台请求URL，后台将作权限拦截，若无可填写'无'或其他">
              <Input v-model="menuForm.path"/>
            </Poptip>
          </FormItem>
          <div v-if="menuForm.type===0">
            <FormItem label="英文名" prop="name">
              <Input v-model="menuForm.name"/>
            </FormItem>
            <FormItem label="图标" prop="icon" style="margin-bottom: 5px;">
              <Input :icon="menuForm.icon" v-model="menuForm.icon"/>
              <span>
                      图标请参考 <a target="_blank" href="https://www.iviewui.com/components/icon"><Icon type="ionic"></Icon> ionicons</a>
                    </span>
            </FormItem>
            <FormItem label="前端组件" prop="component">
              <Input v-model="menuForm.component"/>
            </FormItem>
            <FormItem label="跳转网页链接" prop="url">
              <Poptip trigger="focus" placement="right" width="230" word-wrap title="提示" content="前端组件需为 Monitor 时生效">
                <Input v-model="menuForm.url" placeholder="http://"/>
              </Poptip>
            </FormItem>
          </div>
          <FormItem label="排序值" prop="sortOrder">
            <InputNumber :max="1000" :min="0" v-model="menuForm.sortOrder"></InputNumber>
            <span style="margin-left:5px">值越小越靠前，支持小数</span>
          </FormItem>
          <FormItem label="是否启用" prop="status">
            <i-switch size="large" v-model="menuForm.status" :true-value=0 :false-value=-1>
              <span slot="open">启用</span>
              <span slot="close">禁用</span>
            </i-switch>
          </FormItem>
          <FormItem label="是否显示" prop="status">
            <i-switch size="large" v-model="menuForm.hidden" :true-value=0 :false-value=-1>
              <span slot="open">显示</span>
              <span slot="close">隐藏</span>
            </i-switch>
          </FormItem>
          <Form-item>
            <Button style="margin-right:5px" @click="submitEdit" :loading="submitLoading" type="primary" icon="ios-create-outline">修改并保存</Button>
            <Button @click="handleReset" >重置</Button>
          </Form-item>
        </Form>
        </Col>
      </Row>
    </Card>

    <Modal draggable :title="modalTitle" v-model="menuModalVisible" :mask-closable='false' :width="500" :styles="{top: '30px'}">
      <Form ref="menuFormAdd" :model="menuFormAdd" :label-width="85" :rules="menuFormValidate">
        <div v-if="showParent">
          <FormItem label="上级节点：">
            {{parentTitle}}
          </FormItem>
        </div>
        <FormItem label="类型" prop="type">
          <RadioGroup v-model="menuFormAdd.type">
            <Radio :label="0" :disabled="isButtonAdd">
              <Icon type="ios-list-box-outline" size="16" style="margin-bottom:3px;"></Icon>
              <span>页面菜单</span>
            </Radio>
            <Radio :label="1" :disabled="isMenuAdd">
              <Icon type="md-log-in" size="16" style="margin-bottom:3px;"></Icon>
              <span>操作按钮</span>
            </Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="名称" prop="title" v-if="menuFormAdd.type===0">
          <Input v-model="menuFormAdd.title"/>
        </FormItem>
        <FormItem label="名称" prop="title" v-if="menuFormAdd.type===1">
          <Poptip trigger="focus" placement="right" width="230" word-wrap title="提示" content="操作按钮名称不得重复">
            <Input v-model="menuFormAdd.title"/>
          </Poptip>
        </FormItem>
        <FormItem label="路径" prop="path" v-if="menuFormAdd.type===0">
          <Input v-model="menuFormAdd.path"/>
        </FormItem>
        <FormItem label="请求路径" prop="path" v-if="menuFormAdd.type===1">
          <Poptip trigger="focus" placement="right" width="230" word-wrap title="提示" content="填写后台请求URL，后台将作权限拦截，若无可填写'无'或其他">
            <Input v-model="menuFormAdd.path"/>
          </Poptip>
        </FormItem>
        <div v-if="menuFormAdd.type===0">
          <FormItem label="英文名" prop="name">
            <Input v-model="menuFormAdd.name"/>
          </FormItem>
          <FormItem label="图标" prop="icon"  style="margin-bottom: 5px;">
            <Input :icon="menuFormAdd.icon" v-model="menuFormAdd.icon"/>
            <span>
                  图标请参考 <a target="_blank" href="https://www.iviewui.com/components/icon"><Icon type="ionic"></Icon> ionicons</a>
                </span>
          </FormItem>
          <FormItem label="前端组件" prop="component">
            <Input v-model="menuFormAdd.component"/>
          </FormItem>
          <FormItem label="跳转网页链接" prop="url">
            <Poptip trigger="focus" placement="right" width="230" word-wrap title="提示" content="前端组件需为 Monitor 时生效">
              <Input v-model="menuFormAdd.url" placeholder="http://"/>
            </Poptip>
          </FormItem>
        </div>
        <FormItem label="排序值" prop="sortOrder">
          <InputNumber :max="1000" :min="0" v-model="menuFormAdd.sortOrder"></InputNumber>
          <span style="margin-left:5px">值越小越靠前，支持小数</span>
        </FormItem>
        <FormItem label="是否启用" prop="status">
        <i-switch size="large" v-model="menuFormAdd.status" :true-value=0 :false-value=-1>
          <span slot="open">启用</span>
          <span slot="close">禁用</span>
        </i-switch>
      </FormItem>
        <FormItem label="是否显示" prop="status">
          <i-switch size="large" v-model="menuFormAdd.hidden" :true-value=0 :false-value=-1>
            <span slot="open">显示</span>
            <span slot="close">隐藏</span>
          </i-switch>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="text" @click="cancelAdd">取消</Button>
        <Button type="primary" :loading="submitLoading" @click="submitAdd">提交</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
  import {
    getAllMenuList,
    addPermission,
    editPermission,
    deletePermission
//    searchPermission,
//    getDictDataByType
  } from "@/api/index";
  import { mapActions } from 'vuex'
  import util from "@/libs/util.js";
  export default {
    name: "menu-manage",
    data() {
      return {
        loading: true,
        expandLevel: 1,
        menuModalVisible: false,
        selectList: [],
        selectCount: 0,
        showParent: false,
        searchKey: "",
        parentTitle: "",
        isButtonAdd: false,
        isMenuAdd: false,
        isMenu: false,
        isButton: false,
        editTitle: "",
        modalTitle: "",
        menuForm: {
          mid: "",
          parentId: "",
          buttonType: "",
          hidden:0,
          type: 0,
          sortOrder: null,
          level: null,
          status: 0,
          url: ""
        },
        menuFormAdd: {
          buttonType: ""
        },
        menuFormValidate: {
          title: [{ required: true, message: "名称不能为空", trigger: "blur" }],
          name: [{ required: true, message: "英文名不能为空", trigger: "blur" }],
          icon: [{ required: true, message: "图标不能为空", trigger: "blur" }],
          path: [{ required: true, message: "路径不能为空", trigger: "blur" }],
          component: [
            { required: true, message: "前端组件不能为空", trigger: "blur" }
          ]
        },
        submitLoading: false,
        data: [],
        dcitPermissions: []
      };
    },
    methods: {
      ...mapActions([
        'getRoutersConfig'
      ]),
      init() {
        this.getAllList();
        this.getDictPermissions();
      },
      getDictPermissions() {
//        getDictDataByType("permission_type").then(res => {
//          if (res.success) {
//            this.dcitPermissions = res.result;
//          }
//        });
      },
      handleDropdown(name) {
        if (name === "expandOne") {
          this.expandLevel = 1;
          this.getAllList();
        } else if (name === "expandTwo") {
          this.expandLevel = 2;
          this.getAllList();
        } else if (name === "expandAll") {
          this.expandLevel = 3;
          this.getAllList();
        } else if (name === "refresh") {
          this.getAllList();
        }
      },
      getAllList() {
        this.loading = true;
        getAllMenuList().then(res => {
          this.loading = false;
          if (res.data.code == 200) {
            // 仅展开指定级数 默认所有展开
            let expandLevel = this.expandLevel;
            res.data.data.forEach(function(e) {
              if (expandLevel == 1) {
                if (e.level == 1) {
                  e.expand = false;
                }
                if (e.children && e.children.length > 0) {
                  e.children.forEach(function(c) {
                    if (c.level == 2) {
                      c.expand = false;
                    }
                  });
                }
              } else {
                if (e.children && e.children.length > 0) {
                  e.children.forEach(function(c) {
                    if (expandLevel == 2) {
                      if (c.level == 2) {
                        c.expand = false;
                      }
                    }
                  });
                }
              }
            });
            this.data = res.data.data;
          }
        });
      },
      search() {
        if (this.searchKey) {
          this.loading = true;
//          searchPermission({ title: this.searchKey }).then(res => {
//            this.loading = false;
//            if (res.success) {
//              this.data = res.result;
//            }
//          });
        } else {
          this.getAllList();
        }
      },
      selectTree(v) {
        if (v.length > 0) {
          if (Number(v[0].level) == 1 || Number(v[0].level) == 2) {
            this.isButton = false;
            this.isMenu = true;
          } else {
            this.isButton = true;
            this.isMenu = false;
          }
          if (Number(v[0].status) == 0) {
            this.editStatus = true;
          } else {
            this.editStatus = false;
          }
          // 转换null为""
          for (let attr in v[0]) {
            if (v[0][attr] === null) {
              v[0][attr] = "";
            }
          }
          let str = JSON.stringify(v[0]);
          let menu = JSON.parse(str);
          this.menuForm = menu;
          this.editTitle = menu.title;
        } else {
          this.canelEdit();
        }
      },
      canelEdit() {
        let data = this.$refs.tree.getSelectedNodes()[0];
        if(data){
          data.selected = false;
        }
        this.isMenu = false;
        this.isButton = false;
        this.$refs.menuForm.resetFields();
        delete this.menuForm.mid;
        this.editTitle = "";
      },
      cancelAdd() {
        this.menuModalVisible = false;
      },
      handleReset() {
        let type = this.menuForm.type;
        this.$refs.menuForm.resetFields();
        this.editStatus = true;
        this.menuForm.type = type;
      },
      submitEdit() {
        this.$refs.menuForm.validate(valid => {
          if (valid) {
            if (!this.menuForm.mid) {
              this.$Message.warning("请先点击选择要修改的菜单节点");
              return;
            }
            this.submitLoading = true;
            if (this.menuForm.sortOrder === null) {
              this.menuForm.sortOrder = "";
            }
            if (this.menuForm.type == 1) {
              this.menuForm.name = "";
              this.menuForm.icon = "";
              this.menuForm.component = "";
            }
            editPermission(this.menuForm).then(res => {
              this.submitLoading = false;
              if (res.data.code === 200) {
                this.$Message.success("编辑成功");
                this.menuModalVisible = false;
                this.init()
                this.getRoutersConfig().then(res =>{
                  this.$router.addRoutes(res)
                })
              }
            });
          }
        });
      },
      submitAdd() {
        this.$refs.menuFormAdd.validate(valid => {
          if (valid) {
            this.submitLoading = true;
            if (this.menuFormAdd.sortOrder === null) {
              this.menuFormAdd.sortOrder = "";
            }
            if (this.menuFormAdd.type == 1) {
              this.menuFormAdd.name = "";
              this.menuFormAdd.icon = "";
              this.menuFormAdd.component = "";
            }
            addPermission(this.menuFormAdd).then(res => {
              this.submitLoading = false;
              if (res.data.code === 200) {
                this.$Message.success("添加成功");
                this.menuModalVisible = false;
                this.init()
                this.getRoutersConfig().then(res =>{
                  this.$router.addRoutes(res)
                })
              }
            });
          }
        });
      },
      addMenu() {
        if (this.menuForm.mid == "" || this.menuForm.mid == null) {
          this.$Message.warning("请先点击选择一个菜单权限节点");
          return;
        }
        this.parentTitle = this.menuForm.title;
        this.modalTitle = "添加菜单权限(可拖动)";
        this.showParent = true;
        let type = 0;
        if (this.menuForm.level === '1') {
          type = 0;
          this.isMenuAdd = true;
          this.isButtonAdd = false;
        } else if (this.menuForm.level === '2') {
          type = 1;
          this.isMenuAdd = false;
          this.isButtonAdd = true;
        } else if (this.menuForm.level === '3') {
          this.$Modal.error({
            title: "抱歉，不能添加啦",
            content: "仅支持2级菜单目录"
          });
          return;
        } else {
          type = 0;
          this.isMenuAdd = false;
          this.isButtonAdd = false;
        }
        this.menuFormAdd = {
          type: type,
          parentId: this.menuForm.mid,
          level: Number(this.menuForm.level) + 1+'',
          sortOrder: 1,
          buttonType: "",
          status: 0
        };
        this.menuModalVisible = true;
      },
      addRootMenu() {
        this.modalTitle = "添加一级菜单(可拖动)";
        this.isMenuAdd = true;
        this.isButtonAdd = false;
        this.showParent = false;
        this.menuFormAdd = {
          type: 0,
          level: 1,
          sortOrder: 1,
          status: 0
        };
        this.menuModalVisible = true;
      },
      changeSelect(v) {
        this.selectCount = v.length;
        this.selectList = v;
      },
      delAll() {
        if (this.selectCount <= 0) {
          this.$Message.warning("您还未勾选要删除的数据");
          return;
        }
        this.$Modal.confirm({
          title: "确认删除",
          content: "您确认要删除所选的 " + this.selectCount + " 条数据?",
          onOk: () => {
            let ids = "";
            this.selectList.forEach(function(e) {
              ids += e.mid + ",";
            });
            ids = ids.substring(0, ids.length - 1);
            deletePermission(ids).then(res => {
              if (res.data.code == 200) {
                this.$Message.success("删除成功");
//                util.initRouter(this);
                this.selectList = [];
                this.selectCount = 0;
                this.canelEdit();
                this.init();
                this.getRoutersConfig().then(res =>{
                  this.$router.addRoutes(res)
                })
              }
            });
          }
        });
      }
    },
    mounted() {
      this.init();
    }
  };
</script>

<style>
  .search {
  .operation {
    margin-bottom: 2vh;
  }
  .select-count {
    font-size: 13px;
    font-weight: 600;
    color: #40a9ff;
  }
  .select-title {
    font-size: 12px;
    font-weight: 600;
    color: #40a9ff;
  }
  .select-clear {
    margin-left: 10px;
  }
  .page{
    margin-top: 2vh;
  }
  .drop-down{
    font-size: 13px;
    margin-left: 5px;
  }
  }

  .ivu-poptip {
    display: inline-block;
    width: 100%;
  }

  .ivu-poptip-rel {
    display: inline-block;
    position: relative;
    width: 100%;
  }

  .tree-bar {
    max-height: 500px;
    overflow: auto;
    margin-top: 5px;
  }

  .tree-bar::-webkit-scrollbar {
    width: 6px;
    height: 6px;
  }

  .tree-bar::-webkit-scrollbar-thumb {
    border-radius: 4px;
    -webkit-box-shadow: inset 0 0 2px #d1d1d1;
    background: #e4e4e4;
  }
</style>
